<?php
/**
 * Created by JetBrains PhpStorm.
 * User: thuann89
 * Date: 5/25/12
 * Time: 4:59 PM
 * To change this template use File | Settings | File Templates.
 */
class TopNavMenuWidget extends CWidget
{
    public $locale = '';

    public function run()
    {
        parent::run();
        $data = $this->getData();
        if (count($data))
            $this->renderMenu($data);
    }

    public function getData()
    {
        $localeId = $this->locale!=''?$this->locale: Yii::app()->locale->id;
        $result = FSM::run('Core.Taxonomy.getList', array(
            'module' => 'Site',
            'type' => 'top-navigation',
            'root' => $localeId,
            'state' => 1,
        ));
        $data = $result->data;
        return $data;
    }

    protected function renderMenu($data)
    {
        echo CHtml::openTag('ul', array(
            'id' => 'nav',
            'class' => Yii::app()->locale->id,
        )) . "\n";
        if (count($data['children'])) {
            foreach ($data['children'] as $item) {
                $item['alias'] = str_replace('_' . $this->locale, '', $item['alias']);

                if ($item['alias'] != 'logo')
                    echo "<li> <a href='#' id='" . $item['alias'] . "' class='" . $item['alias'] . "'>{$this->renderName($item['name'])}</a>";
                else echo "<li id='" . $item['alias'] . "'> <a href='#'></a>";

                if (isset($item['children']) && is_array($item['children']) && count($item['children'])) {
                    echo "\n";
                    echo CHtml::openTag('div', array('class' => 'submenu')) . "\n";
                    $this->renderSubMenu($item['children']);
                    echo '<div class="bottom-fragment"> </div>';
                    echo "\n";
                    echo CHtml::closeTag('div') . "\n";
                }
                echo "</li>\n";

            }
        }
        echo CHtml::closeTag('ul') . "\n";
    }

    protected function renderSubMenu($data)
    {
        echo CHtml::openTag('ul') . "\n";
        if (count($data)) {
            foreach ($data as $item) {
                //$data[] = $term;
                echo "<li><a href='#'>{$item['name']}</a>";
                if (isset($item['children']) && is_array($item['children']) && count($item['children'])) {
                    echo "\n";
                    $this->renderSubMenu($item['children']);
                }
                echo "</li>\n";
            }
        }
        echo CHtml::closeTag('ul') . "\n";
    }

    protected function renderName($name){
        return Yii::t('Frontend.Site.topMenu',$name);
    }
}
